<template>
  <div>
    <el-form label-width="80px" label-position="right">
      <el-form-item label-width="0">
        <el-button-group>
          <el-button type="primary" icon="el-icon-circle-plus-outline" :loading="loading" @click="() => { dataSource.splice(0, 0, {})}">数据添加</el-button>
          <el-button type="success" icon="el-icon-check" :loading="loading" @click="saveModelData">数据保存</el-button>
          <el-button type="danger" icon="el-icon-delete" :loading="loading" @click="removeModelData">数据删除</el-button>
          <el-button type="warning" icon="el-icon-download" :loading="loading" @click="exportExcel">导出excel</el-button>
          <el-button type="info" icon="el-icon-upload2" :loading="loading" @click="visible = true">excel导入</el-button>
        </el-button-group>
      </el-form-item>
      <el-form-item label-width="0">
        <el-table v-loading="loading" ref="dataRef" :data="dataSource" stripe border @select="selectSingle" @select-all="selectAll" :height="autoHeight">
          <el-table-column type="index" width="50px" align="center" label="序号"></el-table-column>
          <el-table-column type="selection" width="50px" align="center" label="选择"></el-table-column>
          <el-table-column v-for="column in this.modelInfo.fields" :prop="column.jdbcAlias" :label="column.jdbcComment ||  column.jdbcAlias" :key="column.key" align="center" width="150">
            <template slot="header" slot-scope="scope">
              <div>{{ column.jdbcComment ||  column.jdbcAlias }}</div>
              <el-date-picker v-if="['datetime','date'].includes(column.jdbcType)" type="datetimerange" v-model="filterModel[column.jdbcAlias]" clearable @change="filterChange(column.jdbcAlias)" style="width: 120px" />
              <el-input v-else v-model="filterModel[column.jdbcAlias]" placeholder="过滤" clearable @change="filterChange(column.jdbcAlias)"></el-input>
            </template>
            <template slot-scope="scope">
              <el-input-number v-if="['bigint','decimal','int'].includes(column.jdbcType)" v-model="scope.row[column.jdbcAlias]" :precision="column.jdbcDigit || 0" style="width: 100%" controls-position="right"/>
              <el-switch v-else-if="['bit'].includes(column.jdbcType)" v-model="scope.row[column.jdbcAlias]" />
              <el-date-picker v-else-if="['date'].includes(column.jdbcType)" value-format="yyyy-MM-dd" type="date" v-model="scope.row[column.jdbcAlias]" />
              <el-date-picker v-else-if="['datetime'].includes(column.jdbcType)" value-format="yyyy-MM-dd HH:mm:ss"type="datetime" v-model="scope.row[column.jdbcAlias]" />
              <el-input v-else v-model="scope.row[column.jdbcAlias]"></el-input>
            </template>
          </el-table-column>
        </el-table>
        <div class="lab-table-page">
          <div style="display: inline-flex">
            <el-pagination
                :disabled="loading"
                :current-page="pageInfo.page"
                :page-sizes="[5, 10, 15, 20, 50, 100]"
                :page-size="pageInfo.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageInfo.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
            <el-button-group style="padding: 2px 5px">
              <el-button icon="el-icon-refresh" title="刷新" :disabled="loading" @click="loadSource([])" />
            </el-button-group>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="visible" width="450px" style="text-align: center">
      <el-upload
          :action="uploadUrl"
          :headers="headers"
          :on-success="uploadSuccess"
          :show-file-list="false"
          drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能xlsx文件，且不超过2000行</div>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import IdeaTable from "@/mixins/IdeaTable";

export default {
  name: "ModelData",
  mixins: [IdeaTable],
  inject: {
    modelInfo: {
      type: 'modelInfo',
      default: function () {
        return []
      }
    }
  },
  computed: {
    autoHeight(){
      return `calc(100vh - 420px)`
    },
    uploadUrl () {
      return this.$Util.mergeUrl(process.env.VUE_APP_BASE_API, '/model/importExcel/' + this.modelInfo.callCmd
          + '?query=' + this.$Util.base64Encode(JSON.stringify(this.pageInfo))
          + '&appId=' + this.appInfo.appId)
    },
    headers () {
      return { Authorization: 'Bearer ' + this.$AuthStorage.getAccessToken() }
    }
  },
  created() {
    this.queryUrl = 'model/queryData'
    this.saveUrl = 'model/saveData'
    this.rowKey = this.modelInfo.mainColumn
    this.pageInfo.pageSize = 10
    this.pageInfo.callCmd = this.modelInfo.callCmd
    this.loadSource()
  },
  methods: {
    saveModelData() {
      if (this.selectRowIds.length === 0) {
        this.$resultMsg(this, { msg: '请选择数据'})
        return
      }
      this.pageInfo.datas = this.dataSource.filter(item => this.selectRowIds.includes(item[this.rowKey]))
      this.executeMethod('model/saveData?appId=' + this.appInfo.appId)
    },
    removeModelData() {
      if (this.selectRows.length === 0) {
        this.$resultMsg(this, { msg: '请选择数据'})
        return
      }
      this.$confirm('此操作将会删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.pageInfo.datas = this.selectRows
        this.executeMethod('model/deleteData?appId=' + this.appInfo.appId)
      })
    },
    exportExcel() {
      const query = this.$Util.base64Encode(JSON.stringify(this.pageInfo))
      const url = this.$Util.mergeUrl(process.env.VUE_APP_BASE_API, '/model/exportExcel/')
      window.open(url + this.modelInfo.callCmd + '?query=' + query + '&access_token=' + this.$AuthStorage.getAccessToken() + "&appId=" + this.appInfo.appId)
    },
    uploadSuccess (response) {
      this.$resultMsg(this, response)
      if (response.code === 200) {
        this.loadSource()
        this.visible = false
      }
    },
    executeMethod(url) {
      this.loading = true
      this.$post(url, this.pageInfo)
          .then(res => {
            this.pageInfo.datas = []
            this.$resultMsg(this, res)
            if (res.code === 200) {
              this.loadSource()
            }
            setTimeout(() => {
              this.loading = false
            }, 200)
          })
    }
  }
}
</script>

<style scoped>

</style>
